package com.bjypc.youth.web.excel;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.bjypc.youth.entity.Student;
import com.bjypc.youth.service.IStudentService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 导出青年版数据
 * 
 * @author chenzwei
 * 
 */
public class YouthDataExportExcelAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private IStudentService stuentService;

	public void prepare() throws Exception {
	}

	/**
	 * 绘出Excel
	 * 
	 * @param actionMapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Override
	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		List<Student> dataList = stuentService.findAll();
		HSSFWorkbook workbook = exportExcel(dataList);
		if (workbook != null) {
			this.printExcel(workbook, response, "StudentData");
		}
		return SUCCESS;
	}

	// 导出Excel

	private void printExcel(HSSFWorkbook workbook,
			HttpServletResponse response, String fileName) throws IOException {
		OutputStream out = response.getOutputStream();
		response.setHeader("Content-disposition", "attachment; filename="
				+ fileName + ".xls");
		response.setContentType("application/msexcel;charset=UTF-8");
		workbook.write(out);
		out.flush();
		out.close();

	}

	public HSSFWorkbook exportExcel(List<Student> dataList) throws Exception {
		HSSFWorkbook workbook = this.stuentService.export(dataList);
		return workbook;

	}

	public IStudentService getStuentService() {
		return stuentService;
	}

	public void setStuentService(IStudentService stuentService) {
		this.stuentService = stuentService;
	}

}
